package framework.webserver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;

public class MyWebSocket  extends WebSocketAdapter{
	private static List<Session> sessions = new ArrayList<Session>();
	
	@Override
	public void onWebSocketBinary(byte[] payload, int offset, int len) {
		// TODO Auto-generated method stub
		super.onWebSocketBinary(payload, offset, len);
	}

	@Override
	public void onWebSocketClose(int statusCode, String reason) {
		// TODO Auto-generated method stub
		super.onWebSocketClose(statusCode, reason);
	}

	@Override
	public void onWebSocketConnect(Session sess) {
		// TODO Auto-generated method stub
		super.onWebSocketConnect(sess);
		sessions.add(sess);
	}

	@Override
	public void onWebSocketError(Throwable cause) {
		// TODO Auto-generated method stub
		super.onWebSocketError(cause);
	}

	@Override
	public void onWebSocketText(String message) {
        if (isNotConnected()) {
            return; 
        }
        fireMessage(message);
	}

	public static void fireMessage(String message) {
        for (Session s : sessions) {
        	if (!s.isOpen()) {
        		sessions.remove(s);
        		continue;
        	}
        	try {
				s.getRemote().sendString(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}
}
